package cn.tedu.ivos.filter;

import cn.tedu.ivos.context.AuthenticationContext;
import cn.tedu.ivos.pojo.LoginUser;
import cn.tedu.ivos.utils.JwtUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

public class JwtAuthenticationFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest,
                         ServletResponse servletResponse,
                         FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String authorization = request.getHeader("Authorization");
        if(authorization==null)throw new RuntimeException("请先认证");
        String token=JwtUtils.getRequestToken(request);
        LoginUser user=JwtUtils.parseToken(token, LoginUser.class);
        AuthenticationContext.bindLoginToken(user);
        filterChain.doFilter(servletRequest,servletResponse);
        AuthenticationContext.clearLoginToken();
    }
}
